import {config} from "./http/config.js"
import httpUtil from "./http/httpUtil.js"
import store from "./store/index.js"
const uploadImage = require('./http/upimg/uploadAliyun.js');
export default {
	/**
	 * 跳转再封装，不支持复杂传参。
	 */
	routerTo(path, type, anmin) {
		console.log(path)
		// 判断是否是tabbar
		if(type=="navigateTo"){
			uni.navigateTo({
			    url: path,
				animationType: anmin,
				animationDuration: 300
			});
		}
		if(type=="redirectTo"){
			uni.redirectTo({
			    url: path,
				animationType: anmin,
				animationDuration: 200
			});
		}
		if(type=="reLaunch"){
			uni.reLaunch({
			    url: path,
				animationType: anmin,
				animationDuration: 200
			});
		}
		if(type=="switchTab"){
			uni.switchTab({
			    url: path,
				animationType: anmin,
				animationDuration: 200
			});
		}
		if(type=="navigateBack"){
			uni.navigateBack({
			    delta: 1
			});
		}
		
	},
	routerToLogin(){
		// uni.removeStorageSync('invite_user_id'+store.state.userInfo.id)
		//#ifdef MP-WEIXIN || MP-ALIPAY
			
			// if(uni.getStorageSync('phone')){
			// 	uni.removeStorageSync('token')
			// 	uni.navigateTo({
			// 	    url: '/pages/login/registerStudent?type=1',
			// 		animationType: 'navigateTo',
			// 		animationDuration: 300
			// 	});
			// 	// that.$tools.routerTo('/pages/login/registerStudent?type=1','navigateTo','none')
			// }else{
				uni.navigateTo({
				    url: '/pages/index/bindinfo',
					animationType: 'navigateTo',
					animationDuration: 300
				});
				// that.$tools.routerTo('/pages/index/bindinfo','navigateTo','none')
			// }
			
		//#endif
		
		//#ifdef APP-PLUS
			uni.navigateTo({
				url: '/pages/login/registerStudent',
				animationType: 'navigateTo',
				animationDuration: 300
			});
			// that.$tools.routerTo('/pages/login/registerStudent?type=1','navigateTo','none')
		//#endif
	},
	getDuration(my_time) {  
	  var days    = my_time / 1000 / 60 / 60 / 24;
	  var daysRound = Math.floor(days);
	  var hours = my_time / 1000 / 60 / 60 - (24 * daysRound);
	  var hoursRound = Math.floor(hours);
	  var minutes = my_time / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
	  var minutesRound = Math.floor(minutes);
	  var seconds = my_time / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
	  
	  console.log('转换时间:', daysRound + '天', hoursRound + '时', minutesRound + '分', seconds + '秒');
	  if(daysRound>=2){
		  var time = daysRound
	  }else{
		  if(daysRound>0){
			 var time = daysRound + '天'+ hoursRound + '时'+ minutesRound + '分'+ Math.floor(seconds) + '秒' 
		  }else{
			 var time = hoursRound + '时'+ minutesRound + '分'+ Math.floor(seconds) + '秒' 
		  }
		  
	  }
	  
	  return time;
	},
	openLocation(lat_lng,title){
		uni.openLocation({
			latitude: parseFloat(lat_lng[0]), // 纬度，范围为-90~90，负数表示南纬
			longitude: parseFloat(lat_lng[1]), // 经度，范围为-180~180，负数表示西经
			name: title,
			scale: 28, // 缩放比例          
		})
	},
	// 打电话
	callPhone(phoneNumber = '') {
		let num = phoneNumber.toString()
		uni.makePhoneCall({
			phoneNumber: num,
			fail(err) {
				console.log('makePhoneCall出错', err)
			},
		});
	},
	// 截流函数
	throttle(fn, interval) {
	  var enterTime = 0;//触发的时间
	  var gapTime = interval || 300 ;//间隔时间，如果interval不传，则默认300ms
	  return function() {
	    var context = this;
	    var backTime = new Date();//第一次函数return即触发的时间
	    if (backTime - enterTime > gapTime) {
	      fn.call(context,arguments);
	      enterTime = backTime;//赋值给第一次触发的时间，这样就保存了第二次触发的时间
	    }
	  };
	},
	openLocation(lat_lng,title){
		uni.openLocation({
			latitude: parseFloat(lat_lng[0]), // 纬度，范围为-90~90，负数表示南纬
			longitude: parseFloat(lat_lng[1]), // 经度，范围为-180~180，负数表示西经
			name: title,
			scale: 28, // 缩放比例         
		})
	},
	decodeURIScene(scene){
		let str = decodeURIComponent(scene)
		str=str.split('&')
		let obj={}
		for (let i = 0; i < str.length; i++) {
			str[i]=str[i].split(':')
			obj[str[i][0]]=str[i][1]
		}
		return obj
	},
	request(url, data,type) {
		return new Promise(function(resolve, reject) {
			if(type=='get'){
				httpUtil.GET(url,data,function(res){
					resolve(res);
				},function(err){
					resolve(err);
				})   	
			}else{
				httpUtil.POST(url,data,function(res){
					resolve(res);
				},function(err){
					resolve(err);
				}) 
			}
			           
		})
	},
	// 判断是否登录
	check(cb) {
	  var that = this;
		if(!store.state.userInfo){
			that.newlogin();
		}
	},
	showModal(title, content, showCancel,cd){
		uni.showModal({
			title: title,
			content: content,
			showCancel: showCancel,
			success: function (res) {
				if(typeof cd == "function"){
					cd(res)
				}
			}
		})
	},
	uploadFile(path,cd){
		var self=this
		uni.showLoading({
			mask:true,
			title: "上传中",
		});
		uploadImage({
			filePath: path[0],
			dir: "eyemanager/report/",
			sizeType:['compressed'],
			success: function (res) {
				console.log(res)
				uni.hideLoading()
				if(typeof cd == "function"){
					cd(res)
				}
			},
			fail: function (res) {
				uni.hideLoading()
		
			}
		})
	},
	uploadFileExam(path,cd,name){
		var self=this
		uni.showLoading({
			mask:true,
			title: "上传中",
		});
		uploadImage({
			filePath: path[0],
			name: name,
			dir: "student_card_info/2023_exam/" + name + '_',
			sizeType:['compressed'],
			success: function (res) {
				console.log(res)
				uni.hideLoading()
				if(typeof cd == "function"){
					cd(res)
				}
			},
			fail: function (res) {
				uni.hideLoading()
		
			}
		})
	},
	uploadFileCustomerDir(path,cd,name,dir){
		var self=this
		uni.showLoading({
			mask:true,
			title: "上传中",
		});
		uploadImage({
			filePath: path[0],
			name: name,
			dir: dir + name + '_',
			sizeType:['compressed'],
			success: function (res) {
				console.log(res)
				uni.hideLoading()
				if(typeof cd == "function"){
					cd(res)
				}
			},
			fail: function (res) {
				uni.hideLoading()
		
			}
		})
	},
	upload(path,cd) {
	  uni.showToast({
	    icon: "loading",
	    title: "正在上传"
	  }),
	    uni.uploadFile({
	      url: config.baseURL+"/api/user/common/uploadFile",
	      filePath: path[0], 
	      name: 'file',
	      header: { "Content-Type": "multipart/form-data" },
	      success: function (res) {
			  console.log(res)
			let imgdata=JSON.parse(res.data)
	        if (imgdata.code != 200) { 
	          uni.showModal({
	            title: '提示',
	            content: '上传失败',
	            showCancel: false
	          })
	          return;
	        }
			if(typeof cd == "function"){
				cd(imgdata)
			}
	      },
	      fail: function (e) {
	        uni.showModal({
	          title: '提示',
	          content: '上传失败',
	          showCancel: false
	        })
	      },
	      complete: function () {
	        uni.hideToast();  //隐藏Toast
	      }
	    })
	},
	// 获取二维码
	get_pull_code: function(objs,cb) {
		httpUtil.GET('/api/user/common/getWechatImgByPullId',{pull_id:uni.getStorageSync('wxscene')},function(res){
			if(res.code==200){
				store.commit('wxscenePath', res.data)
				
			}
		})
	},
	addUserBehave: function(objs) {
		httpUtil.POST('/api/user/addUserBehave',objs,function(res){})
	},
	// 埋点
	groupbuy_clue: function(behave,type,num,pull){
		let obj={
			invite_user_id:store.state.userInfo.id,
			behave:behave,
			active:4,
			pull_id:0,
			type:type
		}
		if(uni.getStorageSync('wxscene')){
			obj.pull_id=uni.getStorageSync('wxscene')
		}
		
		if(num){
			obj.share_page=num
		}
		if(uni.getStorageSync('invite_user_id'+store.state.userInfo.id)){
		obj.invite_user_id= uni.getStorageSync('invite_user_id'+store.state.userInfo.id)
		}
		httpUtil.POST('/api/user/groupbuy/refreshClue', obj, function(res) {
		
	  	});  
  },
	
	// 登录获取用户信息
	newlogin: function(cb) {
	  let that = this;
	  var token = wx.getStorageSync('token') || '';
	  uni.login({
	    success: res => {
	      if (res.code) {
	        //发起网络请求
			let objs={
			  code: res.code
			}
			let api;
			// #ifdef  MP-WEIXIN
				api ='/api/user'+config.apiLevel+'/account/login'
			// #endif
			
			// #ifdef  MP-ALIPAY
				api ='/api/user/alipayMini/login'
			// #endif
			//提交信息
	        httpUtil.POST(api,objs,function(res1){
				if(res1.code==200){
					if(res1.data.token){
						store.commit('updateUserinfo', res1.data.userInfo)
						uni.setStorageSync('token', 'Bearer ' + res1.data.token);
					}else{
						uni.removeStorageSync('token');
					}
					
				}
				if(typeof cb == "function"){
					cb(res1)
				}
			},function(err){
				uni.removeStorageSync('token');
				if(typeof cb == "function"){
					cb(err)
				}
			})
		  } else {

	      }
	    },
		fail: res => {
		}
		
	  });
	},
	getStudent(cd,error){
		let that=this
		httpUtil.GET('/api/user' +config.apiLevel+'/student',{}, function(res) {
			store.commit('updateStudent', res.data)
			if(typeof cd == "function"){
				let data = res.data
				cd(data);
			}
		},function(err){
			if(typeof error == "function"){
				error(err);
			}
		}); 
	},
	getUserInfo(cd){
		let that=this
		httpUtil.GET('/api/user/getUserInfo',{}, function(res) {
			if(typeof cd == "function"){
				store.commit('updateUserinfo', res.data)
				cd(res.data);
			}
			
		}); 
	},
	getshoppnum(){
		let that=this
		if(!uni.getStorageSync('token'))return
		httpUtil.GET('/api/user'+config.apiLevel+'/cart',{}, function(res) {
			if(!res.data.online_list)return
			let status=0
			for (let y = 0; y < res.data.course_list.length; y++) {
				if(res.data.course_list[y].is_delete=='hide'){
					status+=1
				}
			}
			if((res.data.online_list.length+res.data.course_list.length-status)>0){
				uni.setTabBarBadge({
				  index: 2,
				  text: (res.data.course_list.length+res.data.online_list.length-status).toString()
				})
			}else{
				uni.hideTabBarRedDot({
					index: 2
				})
			}
		}); 
	},
	getordernum(cd){
		let that=this
		if(!uni.getStorageSync('token'))return
		httpUtil.GET('/api/user'+config.apiLevel+'/order/orderList',{type:'checkout'}, function(res) {
			if(res.data.length>0){
				
				uni.setTabBarBadge({
				  index: 3,
				  text: (res.data.length).toString()
				})
				
			}else{
				uni.hideTabBarRedDot({
					index: 3
				})
			}
			if(typeof cd == "function"){
				cd(res.data.length);
			}
		}); 
	},
	/**
	 * 格式化时间
	 */
	//时间格式化 天时分秒
	format(t) {
		let format = {
			d: '00',
			h: '00',
			m: '00',
			s: '00',
		}
		if (t > 0) {
			let d = Math.floor(t / 86400)
			let h = Math.floor((t / 3600) % 24)
			let m = Math.floor((t / 60) % 60)
			let s = Math.floor(t % 60)
			format.d = d < 10 ? '0' + d : d
			format.h = h < 10 ? '0' + h : h
			format.m = m < 10 ? '0' + m : m
			format.s = s < 10 ? '0' + s : s
		}
		return format
	},
	//时间格式化(格式化最大为小时)
	formatToHours(t) {
		let format = {
			d: '00',
			h: '00',
			m: '00',
			s: '00',
		}
		if (t > 0) {
			let h = Math.floor(t / 3600)
			let m = Math.floor((t / 60) % 60)
			let s = Math.floor(t % 60)

			format.h = h < 10 ? '0' + h : h
			format.m = m < 10 ? '0' + m : m
			format.s = s < 10 ? '0' + s : s
		}
		return format
	},
	// 年月日
	timestamp(timestamp) {
		let date = new Date(timestamp * 1000); //根据时间戳生成的时间对象
		let y = date.getFullYear();
		let m = date.getMonth() + 1;
		let d = date.getDate();

		m = m < 10 ? '0' + m : m;
		d = d < 10 ? '0' + d : d

		let dateText = y + "-" + m + "-" + d
		return dateText
	},
	// 年月日，时分秒
	// "YYYY-mm-dd HH:MM"
	dateFormat(fmt, date) {
		let ret;
		const opt = {
			"Y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"H+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"S+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	},
	/**
	 *  @fn  时间间隔格式化
	 *  @param {*} startTime 开始时间的时间戳
	 *  @param {*} endTime 结束时间的时间戳
	 *  @return {string} str 返回时间字符串
	 */
	getTimeInterval(startTime, endTime) {
		let runTime = parseInt((endTime - startTime) / 1000);
		let year = Math.floor(runTime / 86400 / 365);
		runTime = runTime % (86400 * 365);
		let month = Math.floor(runTime / 86400 / 30);
		runTime = runTime % (86400 * 30);
		let day = Math.floor(runTime / 86400);
		runTime = runTime % 86400;
		let hour = Math.floor(runTime / 3600);
		runTime = runTime % 3600;
		let minute = Math.floor(runTime / 60);
		runTime = runTime % 60;
		let second = runTime;
		let str = '';
		if (year > 0) {
			str = year + '年';
		}
		if (year <= 0 && month > 0) {
			str = month + '月';
		}
		if (year <= 0 && month <= 0 && day > 0) {
			str = day + '天';
		}
		if (year <= 0 && month <= 0 && day <= 0 && hour > 0) {
			str = hour + '小时';
		}
		if (year <= 0 && month <= 0 && day <= 0 && hour <= 0 && minute > 0) {
			str = minute + '分钟';
		}
		if (year <= 0 && month <= 0 && day <= 0 && hour <= 0 && minute <= 0 && second > 0) {
			str += second + '秒';
		}
		str += '前';
		return str;
	},
    updateLastOptions(options) {
        // 检查之前的最后留资是否过期
        const last_options_time = uni.getStorageSync('last_options_time');
        if (last_options_time && new Date().getTime() >= last_options_time) {
            uni.removeStorageSync('last_options_time')
        }
        if (options.scene) {
            uni.setStorageSync('last_options', options);
            uni.setStorageSync('last_options_time', new Date().getTime() + 60 * 24 * 3600 * 1000);
        }
    },
	insertAdminInvite(name) {
	    const last_options = uni.getStorageSync('last_options')
	    if (last_options.scene) {
	        let obj = this.decodeURIScene(last_options.scene)
	        if (obj.scene_id) {
	            let channel_id = 0
	            if (obj.channel_id) {
	                channel_id = obj.channel_id
	            }
	            httpUtil.POST('/api/user/introduce/insertFissionInviteByScene', {
	                scene_id: obj.scene_id,
	                name: name,
	                channel_id: channel_id
	            }, function(result) {})
	        }
	    }
	},
	saveSceneId(options) {
		var scene_id = 0;
		if(options.scene){
			let obj = this.decodeURIScene(options.scene)
			if(obj.scene_id){
				uni.setStorageSync('wxscene',obj.scene_id);
				uni.setStorageSync('wxsceneid',obj.scene_id);
				scene_id = obj.scene_id;
				store.commit('updateWxscene', obj.scene_id);
			}
		}
		if (scene_id == 0) {
			scene_id = uni.getStorageSync('wxscene')
		}
		console.log('tools.saveSceneId', options, scene_id);
		return scene_id;
	},
	
	addBehave(page, type){
		httpUtil.POST('/api/user/addBehave', {scene_type:page,behave:type}, function (res) {
		}) 
	},
	
	/**提示框
	 *title(标题)
	 *icon(图标):  success，loading，none
	 *duration(延时): 0为不关闭, 毫秒数
	 *options(其它参数)
	 */
	toast(title, icon = 'none', options) {
		uni.showToast({
			title: title || '',
			icon: icon,
			duration: (options && options.duration) || 1500,
			image: (options && options.image) || '',
			mask: (options && options.mask) || true,
		});
	}
}
